package ch.qos.logback.classic.sift;


import ch.qos.logback.core.joran.action.Action;
import ch.qos.logback.core.joran.event.InPlayListener;
import ch.qos.logback.core.joran.event.SaxEvent;
import ch.qos.logback.core.joran.spi.ActionException;
import ch.qos.logback.core.joran.spi.InterpretationContext;
import org.xml.sax.Attributes;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @auther czl
 * @date 2019/12/26 15:34
 */
public class SiftAction extends Action implements InPlayListener {
    List<SaxEvent> seList;

    @Override
    public void begin(InterpretationContext ic, String name, Attributes attributes) throws ActionException {
        seList = new ArrayList<SaxEvent>();
        ic.addInPlayListener(this);
    }

    @Override
    public void end(InterpretationContext ic, String name) throws ActionException {
        ic.removeInPlayListener(this);
        Object o = ic.peekObject();
        if (o instanceof ParrelSiftingAppender) {
            ParrelSiftingAppender sa = (ParrelSiftingAppender) o;
            Map<String, String> propertyMap = ic.getCopyOfPropertyMap();
            AppenderFactoryUsingJoran appenderFactory = new AppenderFactoryUsingJoran(seList, sa.getDiscriminatorKey(), propertyMap);
            sa.setAppenderFactory(appenderFactory);
        }
        if (o instanceof ParrelSiftingAppender) {
            ParrelSiftingAppender sa = (ParrelSiftingAppender) o;
            Map<String, String> propertyMap = ic.getCopyOfPropertyMap();
            AppenderFactoryUsingJoran appenderFactory = new AppenderFactoryUsingJoran(seList, sa.getDiscriminatorKey(), propertyMap);
            sa.setAppenderFactory(appenderFactory);
        }

    }

    public void inPlay(SaxEvent event) {
        seList.add(event);
    }

    public List<SaxEvent> getSeList() {
        return seList;
    }

}

